package com.mju.service;

import com.mju.controller.common.JsonResult;
import com.mju.dao.CartDao;
import com.mju.feign.clients.ProductClient;
import com.mju.pojo.Cart;
import com.mju.pojo.Product;
import com.mju.service.ICartService;
import com.mju.service.ex.*;
import com.mju.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartDao cartDao;
    // 需要额外注入商品持久层
    @Autowired
    private ProductClient productClient;

    @Override
    public void addToCart(Integer uid, Integer pid, Integer amount, String username) {
        Cart result = cartDao.selectByUidAndPid(uid, pid);// 目的：看看购物是否有此商品
        Date date = new Date();
        if(result == null) { // 没有此购物车，就添加购物车
            Cart cart = new Cart();
            // 封装数据
            cart.setUid(uid);
            cart.setPid(pid);
            cart.setNum(amount);
            System.out.println("cart:" + cart);
            // 封装价格信息，价格从商品持久层获取。
            JsonResult<Product> data = productClient.getById(pid);
            Product product = data.getData();
            System.out.println("product:" + product);
            cart.setPrice(product.getPrice());

            //封装数据：4个日志
            cart.setCreatedUser(username);
            cart.setCreatedTime(date);
            cart.setModifiedUser(username);
            cart.setModifiedTime(date);

            int rows = cartDao.insert(cart);
            if(rows != 1) {
                throw new InsertException("插入数据时，出现了未知异常。");
            }
        }else {
            // 有此商品，只需累加num
            int num = result.getNum() + amount;
            // 将商品数量更新下，及其日志也更新下。
            result.setNum(num);
            result.setModifiedUser(username);
            result.setModifiedTime(date);
            // 修改数据
            int rows = cartDao.updateById(result);
            if(rows != 1) {
                throw new UpdateException("更新数据时，产生了未知的异常");
            }
        }
    }

    @Override
    public Cart queryCartByUidAndPid(Integer uid, Integer pid) {
        Cart cart = cartDao.selectByUidAndPid(uid, pid);
        if(cart == null) {
            // 添加到购物车中
            addToCart(uid, pid, 1, "管理员");
            Cart newCart = cartDao.selectByUidAndPid(uid, pid);
            return newCart;
        }
        return cart;
    }

    @Override
    public Cart queryCartByCid(Integer cid) {
        return cartDao.selectById(cid);
    }

    @Override
    public List<CartVO> getVOByUid(Integer uid) {
        return cartDao.selectVOByUid(uid);
    }

    @Override
    public Integer addNum(Integer cid, Integer uid, String username) {
        Cart result = cartDao.selectById(cid);
        if(result == null) {
            throw new CartNotFoundException("此数据不存在。");
        }
        if(!result.getUid().equals(uid)) {
            throw new AccessDeniedException("数据非法访问");
        }
        // 修改商品数量
        Integer num = result.getNum() + 1;
        result.setNum(num);
        result.setModifiedUser(username);
        result.setModifiedTime(new Date());
        int rows = cartDao.updateById(result);
        if(rows != 1) {
            throw new UpdateException("更新数据时，产生未知异常。");
        }
        return num;
    }

    @Override
    public Integer subNum(Integer cid, Integer uid, String username) {
        Cart result = cartDao.selectById(cid);
        if(result == null) {
            throw new CartNotFoundException("此数据不存在。");
        }
        if(!result.getUid().equals(uid)) {
            throw new AccessDeniedException("数据非法访问");
        }
        // 修改商品数量
        Integer num = result.getNum() - 1;
        result.setNum(num);
        result.setModifiedUser(username);
        result.setModifiedTime(new Date());
        int rows = cartDao.updateById(result);
        if(rows != 1) {
            throw new UpdateException("更新数据时，产生未知异常。");
        }
        return num;
    }

    @Override
    public List<CartVO> getVOByCids(Integer uid, Integer[] cids) {
        List<CartVO> list = cartDao.selectVOByCids(cids);
        Iterator<CartVO> it = list.iterator();
        while (it.hasNext()) {
            CartVO cart = it.next();
            // 如果当前购物车的数据不属于该用户，就移除。
            if(!cart.getUid().equals(uid)) {
                // 再用迭代器的时候，要删除的话，必须得用它提供的remove()
                it.remove();
            }
        }
        return list;
    }

    @Override
    public Integer deleteCartByCid(Integer cid) {
        int rows = cartDao.deleteById(cid);
        if(rows == 0) {
            throw new DeleteException("服务器异常，删除失败。");
        }
        return rows;
    }

    @Override
    public Integer getCidByPid(Integer pid) {
        return cartDao.getCidByPid(pid);
    }
}
